import { SearchBar, Cascader, Image, Tag, Button, Popup, Toast } from 'antd-mobile'
import { useEffect, useState, useRef } from 'react'
import { transformOptions, getSelected } from '../../utils/index'
import { List as VirtualizedList, AutoSizer } from 'react-virtualized'
import { useNavigate } from 'react-router-dom'
import { FilterOutline, AddSquareOutline } from 'antd-mobile-icons'
import { merchantList, searchList, merchantImport } from '@api'
import './index.scss'

const typeModalStyle = { height: '70vh', padding: '20px', boxSizing: 'border-box', borderRadius: '0 0 15px 15px' }
const Shop = () => {
    const navigate = useNavigate()

    const fileInputRef = useRef(null)

    const [visible1, setVisible1] = useState(false)

    // 筛选开关
    const [filterVisible, setFilterVisible] = useState(false)

    // 筛选数据
    const [selections, setSelections] = useState({})

    // 时间范围
    const [timeRange, setTimeRange] = useState({
        startDate: '',
        endDate: ''
    })

    // 地址
    const [addr, setAddr] = useState([])

    // 筛选数据
    const [categories, setCategories] = useState([])

    // 地址列表
    const [addrData, setAddrData] = useState([])

    // 列表数据
    const [merchant, setMerchant] = useState({})

    // 关键词
    const [keyword, setKeyword] = useState('')

    const [level, setLevel] = useState(null)

    useEffect(() => {
        searchList().then(({ success, data }) => {
            if (success) {
                let arr = []
                let addrArr = []
                data.forEach((item) => {
                    if (item.title === '地址') {
                        addrArr = [...item.options]
                    }
                    if (item.title === '行业类型' || item.title === '检查状态') {
                        arr.push(item)
                    }
                })
                setCategories(arr)
                setAddrData(transformOptions(addrArr))
            }
        })
        getData()
        const obj = JSON.parse(localStorage.getItem('userInfo') || '{}')
        setLevel(obj.level)
    }, [])

    const handleSelect = (categoryID, optionID) => {
        if (categoryID === '检查状态') {
            setSelections((prev) => ({
                ...prev,
                [categoryID]: {
                    [optionID]: true
                }
            }))
        } else {
            setSelections((prev) => ({
                ...prev,
                [categoryID]: {
                    ...prev[categoryID],
                    [optionID]: !(prev[categoryID] && prev[categoryID][optionID])
                }
            }))
        }
    }

    const getColor = (val) => {
        let color = ''
        if (val === 1) {
            color = '#FF0000' // 红色
        } else if (val === 2) {
            color = '#FFFF00' // 黄色
        } else {
            color = '#0000FF' // 蓝色
        }
        return color
    }

    // 列表组件
    const rowRenderer = ({ index, key, style }) => {
        const item = merchant?.records[index] || {}
        return (
            <div className="Shop_item" key={key} style={style} onClick={() => navigate(`shop/${item.id}`)}>
                <div className="Shop_box">
                    <Image src={item.image} fit="contain" width={70} height={70} />
                    <div className="Shop_box_info">
                        <div className="Shop_box_info_title">
                            <p>{item.unit}</p>
                        </div>
                        <Tag color={getColor(item.riskLevel)}>风险等级</Tag>
                        {item.trade.split('/').map((e) => (
                            <Tag key={e} color="primary">
                                {e}
                            </Tag>
                        ))}

                        <p className="Shop_box_info_addr">
                            {item.province}
                            {item.city}
                            {item.area}
                            {item.village}
                            {item.street}
                        </p>
                    </div>
                </div>
            </div>
        )
    }

    // 获取数据
    const getData = () => {
        let a = getSelected(selections)
        let params = {
            keyword,
            current: 1,
            size: 10,
            province: addr[0],
            city: addr[1],
            area: addr[2],
            street: addr[3],
            village: addr[4],
            checkTimeStart: timeRange.startDate ? `${timeRange.startDate} 00:00:00` : '',
            checkTimeEnd: timeRange.endDate ? `${timeRange.endDate} 23:59:59` : '',
            statusName: a['检查状态']?.join(),
            trade: a['行业类型']
        }
        merchantList(params).then(({ success, data, info }) => {
            if (success) {
                setMerchant(data)
            } else {
                Toast.show({ content: info })
                setMerchant([])
            }
        })
    }

    // 关闭类型弹窗
    const closeTypeModal = () => {
        console.log(selections, addr, timeRange)
        getData()
        setFilterVisible(false)
    }

    // 处理日期变更的函数
    const handleDateChange = (e) => {
        const { name, value } = e.target
        console.log(value)
        setTimeRange((prevDates) => ({
            ...prevDates,
            [name]: value
        }))
    }

    // 重置筛选
    const reset = () => {
        setTimeRange({ startDate: '', endDate: '' })
        setSelections({})
        setAddr([])
    }

    // 批量导入
    const handleFileChange = (event) => {
        // 处理文件选择
        const file = event.target.files[0]
        const formData = new FormData()
        formData.append('file', file)
        merchantImport(formData).then(({ success }) => {
            success && getData()
        })
    }

    const handleButtonClick = () => {
        fileInputRef.current.click()
    }

    return (
        <div className="Shop">
            <div className="Shop_head">
                {level === 0 || level === 1 ? <AddSquareOutline onClick={() => navigate('shop/addMerchant')} fontSize={25} /> : null}
                <div className="Shop_head_box">
                    <SearchBar onChange={setKeyword} onBlur={getData} value={keyword} placeholder="请输入店铺名称" />
                </div>
                <FilterOutline fontSize={25} onClick={() => setFilterVisible(true)} />

                <div className="Shop_head_title">
                    <p>数量：{merchant?.total ?? 0}</p>
                    {level === 0 || level === 1 ? <Button color="primary" size="mini" onClick={handleButtonClick}>
                        导入
                    </Button> : null}
                    
                    <Button color="primary" size="mini" onClick={() => navigate('exports')}>
                        批量导出
                    </Button>
                </div>
            </div>
            <Popup position="top" visible={filterVisible} onMaskClick={closeTypeModal} onClose={closeTypeModal} bodyStyle={typeModalStyle}>
                <div className="filter_box">
                    <p className="filter_title">时间范围</p>
                    <div>
                        <input type="date" name="startDate" value={timeRange.startDate} onChange={handleDateChange} />
                        <span>&nbsp;&nbsp;-&nbsp;&nbsp;</span>
                        <input type="date" name="endDate" value={timeRange.endDate} onChange={handleDateChange} />
                    </div>
                    {categories.map((item) => (
                        <div key={item.title}>
                            <p className="filter_title">{item.title}</p>
                            <div className="filter_list">
                                {item.options.map((option) =>
                                    option ? (
                                        <p
                                            className={`${selections[item.title] && selections[item.title][option.option] ? 'active' : ''}`}
                                            key={option.option}
                                            onClick={() => handleSelect(item.title, option.option)}
                                        >
                                            {option.option}
                                        </p>
                                    ) : null
                                )}
                            </div>
                        </div>
                    ))}

                    <p className="filter_title">地址</p>
                    <div className="filter_list2">
                        <p>{addr.join('-')}</p>
                        <Button color="primary" size="mini" onClick={() => setVisible1(true)}>
                            选择地址
                        </Button>
                    </div>
                    <div className="type_btn">
                        <p onClick={reset}>重置</p>
                        <p onClick={closeTypeModal}>确认</p>
                    </div>
                </div>
            </Popup>
            {/* 上传 */}
            <input type="file" style={{ display: 'none' }} ref={fileInputRef} onChange={handleFileChange} />
            {/* 三级联动 */}
            <Cascader
                options={addrData}
                visible={visible1}
                onClose={() => {
                    setVisible1(false)
                }}
                onConfirm={(e) => {
                    setAddr(e)
                }}
            />
            {/* 列表 */}
            <div className="Shop_list">
                <AutoSizer>
                    {({ width, height }) => <VirtualizedList rowCount={merchant?.records?.length ?? 0} rowRenderer={rowRenderer} width={width} height={height} rowHeight={100} overscanRowCount={10} />}
                </AutoSizer>
            </div>
        </div>
    )
}

export default Shop
